﻿using Autofac;
using Common;
using DBContext;
using EV.EventBus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ZoneLine.Common;
using ZoneLine.Models;
using ZoneLine.Models.PrintModeConfig;
using ZoneLine.ViewModels;
using ZoneLine.Views.HStationViews;
using static FreeSql.Internal.GlobalFilter;

namespace ZoneLine.Views
{
    /// <summary>
    /// StationEnableView.xaml 的交互逻辑
    /// </summary>
    public partial class StationEnableView : Window
    {
        public StationEnableView()
        {
            InitializeComponent();
            this.Loaded += StationEnableView_Loaded;
        }

        private bool _canEnter = false;

        private void StationEnableView_Loaded(object sender, RoutedEventArgs e)
        {
            if (Cache.IsPackingProgram)
            {
                opStationGrpb.Visibility = Visibility.Collapsed;
                formulaSelectConfigBtn.Visibility = Visibility.Collapsed;
                formulaConfigInfoBtn.Visibility = Visibility.Collapsed;
                _canEnter = true;
            }
            else
            {
                try
                {
                    var config = StationEnableConfig.GetPara();
                    if (config == null)
                    {
                        DbConfig.DbContext.Insert(new StationEnableConfig()).ExecuteAffrows();
                        config = new StationEnableConfig();
                    }

                    StationOP006.IsChecked = config.OP006StationEnable == 1;
                    StationOP010.IsChecked = config.OP010StationEnable == 1;
                    StationOP020.IsChecked = config.OP020StationEnable == 1;
                    StationOP050L.IsChecked = config.OP050LStationEnable == 1;
                    StationOP050R.IsChecked = config.OP050RStationEnable == 1;
                    //LX.IsChecked = EnableL.IsChecked = true;

                    _canEnter = true;
                }
                catch (Exception ex)
                {
                    HandyControl.Controls.MessageBox.Error("加载系统配置异常" + ex.Message, "温馨提示");
                    return;
                }
            }
        }

        private void BtnEnable(object sender, RoutedEventArgs e)
        {
            if (_canEnter)
            {
                if (LX.IsChecked == true)
                {
                    Cache.Model = ModelEnum.LX;
                }
                else if (SQ.IsChecked == true)
                {
                    Cache.Model = ModelEnum.SQ;
                }
                else if (BQKH.IsChecked == true)
                {
                    Cache.Model = ModelEnum.BQKH;
                }
                else if (BQLH.IsChecked == true)
                {
                    Cache.Model = ModelEnum.BQLH;
                }
                else if (WL.IsChecked == true)
                {
                    Cache.Model = ModelEnum.WL;
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error("请选择客户！","温馨提示");
                    return;
                }

                if (string.IsNullOrEmpty( Cache.CurrentProductType))
                {
                    HandyControl.Controls.MessageBox.Error("请选择产品！", "温馨提示");
                    return;
                }

                var workDirection = 0;
                if (EnableL.IsChecked.HasValue && EnableL.IsChecked.Value)
                {
                    workDirection = 1;
                    Cache.WorkDirection = Common.WorkDirectionEnum.Left;
                }
                else if (EnableR.IsChecked.HasValue && EnableR.IsChecked.Value)
                {
                    workDirection = 2;
                    Cache.WorkDirection = Common.WorkDirectionEnum.Right;
                }
                else {
                    HandyControl.Controls.MessageBox.Error("请选择型号！", "温馨提示");
                    return;
                }

                

                if (Cache.IsPackingProgram)//装箱程序
                {
                    var view = new PackingMainView();
                    view.Show();
                    App.Current.MainWindow = view;
                    this.Close();
                }
                else
                {
                    //验证配方：
                    //if (!VerifyCurrentFormula()) return;

                    var dal = ContainerServer.Container.Resolve<IModelDAL>();
                    var saveRlt = dal.UpdateModel<StationEnableConfig>(p => true, s =>
                         new StationEnableConfig()
                         {
                             OP006StationEnable = StationOP006.IsChecked == true ? 1 : 0,
                             OP010StationEnable = StationOP010.IsChecked == true ? 1 : 0,
                             OP020StationEnable = StationOP020.IsChecked == true ? 1 : 0,
                             OP050LStationEnable = StationOP050L.IsChecked == true ? 1 : 0,
                             OP050RStationEnable = StationOP050R.IsChecked == true ? 1 : 0,
                             WorkDirection = workDirection,
                         }
                    );
                    if (saveRlt)
                    {
                        StationEnableConfig.Reload();
                        var view = new MainWindow();
                        view.Show();
                        App.Current.MainWindow = view;
                        this.Close();
                        MessageCenter.PublishAsync("CloesQStationEnable");
                    }
                }
               
            }
        }

        private List<string> _productionTypes;

        public List<string> ProductionTypes
        {
            get { return _productionTypes; }
            set { value = _productionTypes; }
        }

        private bool VerifyCurrentFormula()
        {
            if (Cache.CurrentFormula.Count < 3)
            {
                HandyControl.Controls.MessageBox.Error($"配方未选择，请将所有设备切换到【手动】【在线】模式选择配方！", "温馨提示");
                return false;
            }

            var diffCurrentProductType = Cache.CurrentFormula.Select(o => o.CurrentProductType).Distinct().ToList();
            if (diffCurrentProductType.Count > 1)
            {
                HandyControl.Controls.MessageBox.Error($"当前选择的配方中存在产品不一致的工位，请检查配方选择！", "温馨提示");
                return false;
            }

            var diffWorkDirection = Cache.CurrentFormula.Select(o => o.WorkDirection).Distinct().ToList();
            if (diffWorkDirection.Count > 1)
            {
                HandyControl.Controls.MessageBox.Error($"当前选择的配方中存在型号不一致的工位，请检查配方选择！", "温馨提示");
                return false;
            }

            foreach (var item in Cache.CurrentFormula)
            {
                if (item.WorkDirection != Cache.WorkDirection)
                {
                    HandyControl.Controls.MessageBox.Error($"型号选择错误，当前型号是:{(item.WorkDirection == Common.WorkDirectionEnum.Left ? "左" : item.WorkDirection == Common.WorkDirectionEnum.Right ? "右" : "未配置")}", "温馨提示");
                    return false;
                }

                if (item.Model != Cache.Model)
                {
                    HandyControl.Controls.MessageBox.Error($"型号选择错误，当前型号是:{(item.Model.GetDisplayName())}", "温馨提示");
                    return false;
                }

                if (item.CurrentProductType != Cache.CurrentProductType)
                {
                    HandyControl.Controls.MessageBox.Error($"型号选择错误，当前型号是:{item.CurrentProductType}", "温馨提示");
                    return false;
                }
            }
            return true;
        }


        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var current = sender as ComboBox;
                var selectVal = current.SelectedValue?.ToString();
                if (selectVal != null)
                {
                    Cache.CurrentProductType = selectVal;
                }
                else {
                    throw new Exception();
                }
                if (LX.IsChecked == true)
                {
                    var other = DbConfig.DbContext.Queryable<LXQC_Config>().ToList();
                    foreach (var item in other)
                    {
                        if (item.ProductType == Cache.CurrentProductType)
                        {
                            DbConfig.DbContext.Update<LXQC_Config>().Set(a => a.IsEnabled == true).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                        else
                        {
                            DbConfig.DbContext.Update<LXQC_Config>().Set(a => a.IsEnabled == false).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                    }
                }
                else if (SQ.IsChecked == true)
                {
                    var other = DbConfig.DbContext.Queryable<SQQC_Config>().ToList();
                    foreach (var item in other)
                    {
                        if (item.ProductType == Cache.CurrentProductType)
                        {
                            DbConfig.DbContext.Update<SQQC_Config>().Set(a => a.IsEnabled == true).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                        else
                        {
                            DbConfig.DbContext.Update<SQQC_Config>().Set(a => a.IsEnabled == false).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                    }
                }
                else if (BQKH.IsChecked == true)
                {
                    var other = DbConfig.DbContext.Queryable<BQQC_KH_Config>().ToList();
                    foreach (var item in other)
                    {
                        if (item.ProductType == Cache.CurrentProductType)
                        {
                            DbConfig.DbContext.Update<BQQC_KH_Config>().Set(a => a.IsEnabled == true).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                        else
                        {
                            DbConfig.DbContext.Update<BQQC_KH_Config>().Set(a => a.IsEnabled == false).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                    }
                }
                else if (BQLH.IsChecked == true)
                {
                    var other = DbConfig.DbContext.Queryable<BQQC_LH_Config>().ToList();
                    foreach (var item in other)
                    {
                        if (item.ProductType == Cache.CurrentProductType)
                        {
                            DbConfig.DbContext.Update<BQQC_LH_Config>().Set(a => a.IsEnabled == true).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                        else
                        {
                            DbConfig.DbContext.Update<BQQC_LH_Config>().Set(a => a.IsEnabled == false).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                    }
                }
                else if (WL.IsChecked == true)
                {
                    var other = DbConfig.DbContext.Queryable<WLQCConfig>().ToList();
                    foreach (var item in other)
                    {
                        if (item.ProductType == Cache.CurrentProductType)
                        {
                            DbConfig.DbContext.Update<WLQCConfig>().Set(a => a.IsEnabled == true).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                        else
                        {
                            DbConfig.DbContext.Update<WLQCConfig>().Set(a => a.IsEnabled == false).Where(w => w.ProductType.Equals(item.ProductType)).ExecuteAffrows();
                        }
                    }
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error($"必须选择型号后才能进入工作流程！", "温馨提示");
                    return;
                }
            }
            catch
            {
                HandyControl.Controls.MessageBox.Error($"未查询到产品信息！", "温馨提示");
                return;
            }
        }

        private void CheckedRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton checkedRadioButton = sender as RadioButton;
            if (checkedRadioButton != null)
            {
                if (ProductionTypes == null)
                {
                    try
                    {
                        List<string> list = default;
                        switch (checkedRadioButton.Name)
                        {
                            case "LX":
                                list = DbConfig.DbContext.Queryable<LXQC_Config>().ToList().Select(s => s.ProductType).ToList();
                                break;
                            case "SQ":
                                list = DbConfig.DbContext.Queryable<SQQC_Config>().ToList().Select(s => s.ProductType).ToList();
                                break;
                            case "BQKH":
                                list = DbConfig.DbContext.Queryable<BQQC_KH_Config>().ToList().Select(s => s.ProductType).ToList();
                                break;
                            case "BQLH":
                                list = DbConfig.DbContext.Queryable<BQQC_LH_Config>().ToList().Select(s => s.ProductType).ToList();
                                break;
                            case "WL":
                                list = DbConfig.DbContext.Queryable<WLQCConfig>().ToList().Select(s => s.ProductType).ToList();
                                break;
                            default:
                                list = new List<string>();
                                break;
                        }
                        cmb_productType.ItemsSource = ProductionTypes = list;
                        cmb_productType.Items.Refresh();
                    }
                    catch
                    {

                    }
                }
            }
        }
        
        /* //Old
        private void LX_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton checkedRadioButton = sender as RadioButton;
            if (checkedRadioButton != null)
            {
                if (ProductionTypes == null)
                {
                    var lxqc = DbConfig.DbContext.Queryable<LXQC_Config>().ToList();
                    cmb_productType.ItemsSource = ProductionTypes = lxqc.Select(s => s.ProductType).ToList();
                    cmb_productType.Items.Refresh();
                }
            }
        }

        private void SQ_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton checkedRadioButton = sender as RadioButton;
            if (checkedRadioButton != null)
            {
                if (ProductionTypes == null)
                {
                    try
                    {
                        var lxqc = DbConfig.DbContext.Queryable<SQQC_Config>().ToList();
                        cmb_productType.ItemsSource = ProductionTypes = lxqc.Select(s => s.ProductType).ToList();
                        cmb_productType.Items.Refresh();
                    }
                    catch
                    {
                    }
                }
            }
        }

        private void BQKH_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton checkedRadioButton = sender as RadioButton;
            if (checkedRadioButton != null)
            {
                if (ProductionTypes == null)
                {
                    try
                    {
                        var lxqc = DbConfig.DbContext.Queryable<BQQC_KH_Config>().ToList();
                        cmb_productType.ItemsSource = ProductionTypes = lxqc.Select(s => s.ProductType).ToList();
                        cmb_productType.Items.Refresh();
                    }
                    catch
                    {
                    }
                }
            }
        }

        private void BQLH_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton checkedRadioButton = sender as RadioButton;
            if (checkedRadioButton != null)
            {
                if (ProductionTypes == null)
                {
                    try
                    {
                        var lxqc = DbConfig.DbContext.Queryable<BQQC_LH_Config>().ToList();
                        cmb_productType.ItemsSource = ProductionTypes = lxqc.Select(s => s.ProductType).ToList();
                        cmb_productType.Items.Refresh();
                    }
                    catch
                    {
                    }
                }
            }
        }

        private void WL_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton checkedRadioButton = sender as RadioButton;
            if (checkedRadioButton != null)
            {
                if (ProductionTypes == null)
                {
                    try
                    {
                        var lxqc = DbConfig.DbContext.Queryable<WLQCConfig>().ToList();
                        cmb_productType.ItemsSource = ProductionTypes = lxqc.Select(s => s.ProductType).ToList();
                        cmb_productType.Items.Refresh();
                    }
                    catch
                    {
                    }
                }
            }
        }
        */



        private void PackageUpdateView(object sender, RoutedEventArgs e)
        {
            AuthView authView = new AuthView(() => {
                PackageUpdateView packageUpdateView = new PackageUpdateView();
                packageUpdateView.Show();
            });
            authView.ShowDialog();
        }

        private void SelectFormulaConfig(object sender, RoutedEventArgs e)
        {
            AuthView authView = new AuthView(() => {
                FormulaSelectView formulaSelectView = new FormulaSelectView();
                formulaSelectView.Show();
            });
            authView.ShowDialog();

        }

        private void SetFormulaConfig(object sender, RoutedEventArgs e)
        {
            AuthView authView = new AuthView(() => {
                FormulaConfigView formulaConfigView = new FormulaConfigView();
                formulaConfigView.Show();
            });
            authView.ShowDialog();
        }

        private void EnableL_Checked(object sender, RoutedEventArgs e)
        {
            if (EnableL.IsChecked.HasValue && EnableL.IsChecked.Value)
            {
                Cache.WorkDirection = Common.WorkDirectionEnum.Left;
            }
        }

        private void EnableR_Checked(object sender, RoutedEventArgs e)
        {
            if (EnableR.IsChecked.HasValue && EnableR.IsChecked.Value)
            {
                Cache.WorkDirection = Common.WorkDirectionEnum.Right;
            }
        }

    }
}